﻿using StarryEdge.Core;
using StarryEdge.Core.Attributes;
using StarryEdge.Core.Models.Interact;
using StarryEdge.Core.Models;
using StarryEdge.Core.Tool;
using StarryEdge.UserCore;
using StarryEdge.UserCore.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;

namespace StarryEdge.Module.Parameter
{
    [Singleton]
    public class SettingParameter : InitFileBase, ISettingParameter
    {
        private SettingModel _setting;
        private TestModel _test;
        public SettingParameter(IStarryEdgeLog starryEdgeLog) : base(starryEdgeLog, "parameter", "parameter")
        {
            _log.LogRun("注册成功");
            if (File.Exists(_path))
            {
                string str = base.Read();
                if (!string.IsNullOrEmpty(str))
                {
                    Dictionary<string, object> keyValues = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(str);
                    try
                    {
                        _setting = System.Text.Json.JsonSerializer.Deserialize<SettingModel>(keyValues[nameof(SettingModel)].ToString());
                        _test = System.Text.Json.JsonSerializer.Deserialize<TestModel>(keyValues[nameof(TestModel)].ToString());
                    }
                    catch (Exception ex)
                    {
                        _log.LogRun($"系统参数初始化异常：{ex}", Core.Enums.LogLevel.Error);
                        _test = new TestModel();
                    }
                }
            }
            else
            {
                _setting = new SettingModel();
            }
        }

        public object GetModel(string type)
        {
            switch (type)
            {
                case nameof(SettingModel):
                    return _setting;
                case nameof(TestModel):
                    return _test;
            }
            return default;
        }

        public void Save()
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add(nameof(SettingModel), _setting);
            data.Add(nameof(TestModel), _test);
            Save(System.Text.Json.JsonSerializer.Serialize(data, OptionsHelper.Options));
        }

    }
}
